<?php

class DbProduct extends DbModel{

	public $table_name = "products";
	public $order = "name";

	public function get($id){
		$product = $this->row(array(
			"conditions" => array("id"=>$id)
		));

		$product["images"] = $this->find(array(
			"from" => "product_images",
			"conditions" => array("product_id"=>$id),
			"order" => "position asc"
		));

		
		$product["category_ids"] = $this->indexed(array(
			"from" => "product_categories INNER JOIN categories ON categories.id=product_categories.category_id",
			"conditions" => array("product_id"=>$id)
		));
		return $product;
	}

	public function addImage($product_id, $filename){
		$ret = false;
		$pos = (int)$this->field("pos", array("select"=>"IFNULL(MAX(position)+1,0) as pos","from"=>"product_images","conditions"=>array("product_id"=>$product_id)));
		$product = $this->row(array("conditions"=>array("id"=>$product_id)));
		if($product){
			$sql = "INSERT INTO product_images(product_id,src,position) VALUES($product_id,'$filename',$pos)";
			$ret = $this->exec($sql);
		}
		return $ret;
	}

	public function getImage($product_id, $filename){
		return $this->row(array(
			"from" => "product_images",
			"order" => "position",
			"conditions" => array("product_id"=>$product_id,"src"=>$filename)
		));
	}

	public function save($data){
		$ret = false;
		
		//validate data
		if(empty($data["code"]) || empty($data["name"]) || (int)$data["category_id"]==0) {
			$this->errors = array("Uneti podaci nisu validni. Proverite polja označena zvezdicom, ona su obavezna.");
			return false;
		}

		//save the product
		$data["price"] = (float)$data["price"];
		if((int)$data["id"]>0){
			$sql = "UPDATE products SET "
					."`code` = '".$data["code"]."', "
				  	."`name` = '".$data["name"]."',"
				  	."`price` = ".$data["price"].","
				  	."`desc` = '".$data["desc"]."',"
				  	."`discount` = ".((int)$data["discount"])
				  ." WHERE id=".$data["id"];
		}else{
			$sql = "INSERT INTO products(`code`,`name`,`price`,`desc`,`discount`)"
				  ."VALUES ('".$data["code"]."','".$data["name"]."',".$data["price"].",'".$data["desc"]."',".((int)$data["discount"]).")";
		}
		$ret = $this->exec($sql);
		if((int)$data["id"] < 1){
			$data["id"] = $this->field("id", array(
				"from" => "products",
				"conditions" => array(
					"name" => $data["name"],
					"price" => $data["price"]
				),
				"order" => "id DESC"
			));
		}
		//save categories
		$ret = $ret && $this->exec("DELETE FROM product_categories WHERE product_id=".$data["id"]);
		if((int)$data["category_id"]>0){
			$ret = $ret && $this->exec("INSERT INTO product_categories VALUES(".$data["id"].",".$data["category_id"].")");
		}
		//save images
		if(!$data["image"]){
			$data["image"] = array();
		}

		$imagesnottodelete = array();
		foreach($data["image"] as $image){
			$imagesnottodelete[] = $image["src"];
		}

		//remove deleted images from disk
		empty_dir(DIR_IMAGE . "/products/".$data["id"], $imagesnottodelete);
		//remove all images from db
		$ret = $ret && $this->exec("DELETE FROM product_images WHERE product_id=".$data["id"]);
		//save images
		foreach ($data["image"] as $id=>$image){
			if($id>0){
				$sql = "INSERT INTO product_images(id, product_id, src, position, description) "
					  ."VALUES($id, ".$data["id"].",'".$image["src"]."',".$image["position"].", '".$image["description"]."')";
			}
			$ret = $ret && $this->exec($sql);
		}

		return $ret;
	}

	public function search($categories=array(), $page=1, $per_page=ITEMS_PER_PAGE){
		if(!is_array($tags)){
			$categories = array($categories);
		}
		$products = array();
		$total = 0;

		$options = array(
			"select" => "DISTINCT products.*",
			"from" => "product_categories inner join products on products.id=product_categories.product_id",
			"conditions" => array(
				"and" => array(
					"product_categories.category_id" => $categories
				)
			),
			"order" => "products.name"
		);
		$total = $this->count($options);

		$options["offset"] = array($page,$per_page);
		$ids = $this->find($options);
		if($ids){
			foreach($ids as $row){
				$products[] = $this->get($row["id"]);
			}
		}
		return array($products, $total);
	}

	public function delete($id){
		$sql = "DELETE pi.*,p.*,pc.* "
			  ."FROM products p LEFT JOIN product_images pi on p.id=pi.product_id LEFT JOIN product_categories pc ON p.id=pc.product_id "
			  ."WHERE p.id=$id";
		return $this->exec($sql);
	}
	
	public function findWithImage($options) {
		$options["select"] = "p.*, pi.src as `image`";
		$options["from"] = "products p LEFT JOIN (SELECT * FROM product_images ORDER BY position) AS `pi` ON p.id=pi.product_id LEFT JOIN product_categories pc ON p.id=pc.product_id";
		$options["group"] = "p.id";
		$options["order"] = "p.{$this->order}, pi.position";
		return $this->find($options);
	}
	
	public function buildConditionsFromSearch($params) {
		$conditions = array();
		removeEmptyItems($params);
		
		if(!empty($params)) {
			$conditions = array(
				"AND" => array()
			);
			if($params["keyword"]) {
				$conditions["OR"] = array();
				$conditions["OR"]["`name` LIKE"] = "'%".$params["keyword"]."%'";
				$conditions["OR"]["`desc` LIKE"] = "'%".$params["keyword"]."%'";
			}
			if($params["price_from"]) {
				$conditions["AND"]["price >="] = $params["price_from"];
			}
			if($params["price_to"]) {
				$conditions["AND"]["price <="] = $params["price_to"];
			}
			if($params["category_id"]) {
				$conditions["AND"]["pc.category_id"] = $params["category_id"];
			}
		}
		return empty($conditions) ? false : $conditions;
	}
}

?>